/*
@auther fenglei
*/
package gin_server

import (
	"time"

	"github.com/gin-gonic/gin"
)

// 默认超时配置
const (
	DefaultReadTimeout  = 10 * time.Second
	DefaultWriteTimeout = 10 * time.Second
)

// ServerOptions 服务器超时配置选项
type ServerOptions struct {
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

// NewServerOptions 创建默认超时配置
func NewServerOptions() *ServerOptions {
	return &ServerOptions{
		ReadTimeout:  DefaultReadTimeout,
		WriteTimeout: DefaultWriteTimeout,
	}
}

// WithReadTimeout 设置读超时
func (opts *ServerOptions) WithReadTimeout(timeout time.Duration) *ServerOptions {
	opts.ReadTimeout = timeout
	return opts
}

// WithWriteTimeout 设置写超时
func (opts *ServerOptions) WithWriteTimeout(timeout time.Duration) *ServerOptions {
	opts.WriteTimeout = timeout
	return opts
}

type server interface {
	ListenAndServe() error
}

// RunWindowsServer 启动Windows服务器，支持可选的超时配置
func RunWindowsServer(address string, routers *gin.Engine, opts ...*ServerOptions) error {
	if address == "" {
		panic("address is required")
	}
	if routers == nil {
		panic("routers is required")
	}

	// 使用默认超时值
	readTimeout := DefaultReadTimeout
	writeTimeout := DefaultWriteTimeout

	// 如果提供了配置选项，使用自定义超时值
	if len(opts) > 0 && opts[0] != nil {
		if opts[0].ReadTimeout > 0 {
			readTimeout = opts[0].ReadTimeout
		}
		if opts[0].WriteTimeout > 0 {
			writeTimeout = opts[0].WriteTimeout
		}
	}

	s := initServer(address, routers, readTimeout, writeTimeout)
	err := s.ListenAndServe()
	if err != nil {
		return err
	}
	return nil
}

// RunWindowsServerWithDefaults 使用默认超时值启动Windows服务器（保持向后兼容）
func RunWindowsServerWithDefaults(address string, routers *gin.Engine) error {
	return RunWindowsServer(address, routers)
}
